//
//  JYTTelephoneViewController.m
//  JYT_IOS
//
//  Created by nxa-chengjinhui on 2017/1/4.
//  Copyright © 2017年 nxa-yuanguoxiang. All rights reserved.
//

#import "JYTTelephoneViewController.h"

@interface JYTTelephoneViewController ()<UITextFieldDelegate>
{
    NSTimer *timer;
    NSInteger timeCount;
}
@property (nonatomic,strong) UITextField *phoneTextfild;//手机

@property (nonatomic,strong) UITextField *testTextfild;//验证码

@property (nonatomic,strong) UIButton *testBtn;


@end

@implementation JYTTelephoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    NSDictionary *dic = @{@"lftBtnBgImg":@"ic_goback",
                          @"lftBtnTitle":@"no",
                          @"pageTitle":@"修改手机号码",
                          @"rhtBtnBgImg":@"no",
                          @"rhtBtnTitle":@"no"};
    
    [self setNavgationBarWithDic:dic];

    //手机号码
    UILabel *phoneLab = [[UILabel alloc] initWithFrame:CGRectMake(20, 64+20, 60, 40)];
    phoneLab.text = @"手机";
    phoneLab.font = [UIFont systemFontOfSize:16];
    phoneLab.adjustsFontSizeToFitWidth = YES;
    phoneLab.textAlignment = NSTextAlignmentCenter;
    phoneLab.backgroundColor = kColor(244, 244, 244);
    [self.view addSubview:phoneLab];
    
    self.phoneTextfild = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(phoneLab.frame), 84,CURRENT_SCREEN_WIDTH-40-phoneLab.frame.size.width, 40)];
    self.phoneTextfild.placeholder = @"请填写新的手机号码";
    self.phoneTextfild.backgroundColor = kColor(244, 244, 244);
    self.phoneTextfild.delegate = self;
    [self.view addSubview:self.phoneTextfild];
    UIView *blankView1 = [[UIView alloc] initWithFrame:CGRectMake(self.phoneTextfild.frame.origin.x,self.phoneTextfild.frame.origin.y,5, self.phoneTextfild.frame.size.height)];
    self.phoneTextfild.leftView = blankView1;
    self.phoneTextfild.leftViewMode =UITextFieldViewModeAlways;  // 这里是用来设置leftView的实现时机的
    
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(phoneLab.frame), phoneLab.frame.origin.y+7, 1.5, 24)];
    line1.backgroundColor = [UIColor grayColor];
    [self.view addSubview:line1];
    
    //验证码
    UILabel *testLab = [[UILabel alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(phoneLab.frame)+20, 60, 40)];
    testLab.text = @"验证码";
    testLab.font = [UIFont systemFontOfSize:16];
    testLab.adjustsFontSizeToFitWidth = YES;
    testLab.textAlignment = NSTextAlignmentCenter;
    testLab.backgroundColor = kColor(244, 244, 244);
    [self.view addSubview:testLab];
    
    self.testTextfild = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(testLab.frame), CGRectGetMaxY(phoneLab.frame)+20,CURRENT_SCREEN_WIDTH-40-testLab.frame.size.width-CURRENT_SCREEN_WIDTH/3, 40)];
    self.testTextfild.placeholder = @"请填写验证码";
    self.testTextfild.backgroundColor = kColor(244, 244, 244);
    self.testTextfild.delegate = self;
//    self.testTextfild.leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"02驾校查询_24"]];
//    self.testTextfild.leftViewMode = UITextFieldViewModeAlways;
    [self.view addSubview:self.testTextfild];
    
    UIView *blankView = [[UIView alloc] initWithFrame:CGRectMake(self.testTextfild.frame.origin.x,self.testTextfild.frame.origin.y,5, self.testTextfild.frame.size.height)];
    self.testTextfild.leftView = blankView;
    self.testTextfild.leftViewMode =UITextFieldViewModeAlways;  // 这里是用来设置leftView的实现时机的

    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(testLab.frame), testLab.frame.origin.y+7, 1.5, 24)];
    line2.backgroundColor = [UIColor grayColor];
    [self.view addSubview:line2];
    
    //发送验证码
    self.testBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.testBtn.frame = CGRectMake(CURRENT_SCREEN_WIDTH-140, self.testTextfild.frame.origin.y, 120, 40);
    [self.testBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
    [self.testBtn addTarget:self action:@selector(sendNumber) forControlEvents:UIControlEventTouchUpInside];
    self.testBtn.layer.masksToBounds = YES;
    self.testBtn.layer.cornerRadius = 5;
    self.testBtn.backgroundColor = kColor(241, 241, 241);
    [self.testBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.testBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:self.testBtn];
    
    //确认
    UIButton *comfireBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    comfireBtn.frame = CGRectMake(20, CGRectGetMaxY(self.testTextfild.frame)+20 ,CURRENT_SCREEN_WIDTH-40, 40);
    [comfireBtn setBackgroundColor:kColor(58, 150, 248)];
    [comfireBtn setTitle:@"确定" forState:UIControlStateNormal];
    comfireBtn.layer.masksToBounds = YES;
    comfireBtn.layer.cornerRadius = 5;
    [comfireBtn addTarget:self action:@selector(comfireBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:comfireBtn];
}
//获取验证码事件
-(void)sendNumber{
    [self.phoneTextfild resignFirstResponder];
    /*
     *  1.判断手机号格式是否正确
     *
     *  2.发送请求是否成功
     *
     */

    NSString *phone = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\d{8}$";
    NSPredicate *testPhone = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phone];
    if ([testPhone evaluateWithObject:self.phoneTextfild.text]) {
        //发起请求
        JYTHttpClient *manager = [JYTHttpClient sharedInstance];
        manager.urlType = userZoneUrl;
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:self.phoneTextfild.text forKey:@"TelPhone"];
//        [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"username"] forKey:@"UserName"];
        [dic setObject:@"SendVerfiyPwd" forKey:@"CommandCode"];
        
        [manager post:@"GetDataInfo" withParam:dic];
        
        manager.finishCallbackHandler = ^(id result, NSString *code, NSString *msg){
            
//            NSDictionary *dic = result;
            //            dic = dic[@"data"];
            
            MyLog(@"获取验证=====\n\n%@", code);
            timeCount=60;
            timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerClick:) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
            self.testBtn.userInteractionEnabled = NO;
            [JYTPublicClass showMessage:@"验证码已发送，请注意查看手机信息"];
        };
        
        manager.errorCallbackHandler = ^(NSString * code, NSString * msg) {
            MyLog(@"000000011111获取验证失败");
            if ([code isKindOfClass:[NSNull class]]) {
                MyLog(@"原因=====\n\n%@", msg);
            }else{
                if ([code isEqualToString:@"-1"]) {
                    [JYTPublicClass showMessage:@"服务器异常，请稍后再试！"];
                }else{
                    [JYTPublicClass showMessage:@"当前网络异常，请稍后再试！"];
                }
            }
        };
    }else{
        [JYTPublicClass showMessage:@"请输入正确手机号"];
    }
}
-(void)timerClick:(NSTimer *)timerr{
    
    [self.testBtn setTitle:[NSString stringWithFormat:@"%ld秒",timeCount] forState:UIControlStateNormal];
    if (timeCount==0) {
        [self.testBtn setTitle:@"重新发送" forState:UIControlStateNormal];
        [timerr invalidate];
        timerr = nil;
        self.testBtn.userInteractionEnabled = YES;
    }
    timeCount--;
}

//确认修改手机号码事件
-(void)comfireBtnClicked{
    MyLog(@"112e12ewa");
        //发起请求
        JYTHttpClient *manager = [JYTHttpClient sharedInstance];
    
        manager.urlType = userZoneUrl;
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:self.phoneTextfild.text forKey:@"telPhone"];
        [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"username"] forKey:@"username"];
        [dic setObject:self.testTextfild.text forKey:@"code"];
        [dic setObject:@"ModifyTel" forKey:@"CommandCode"];
        
        [manager post:@"UpdateDataInfo" withParam:dic];
        
        manager.finishCallbackHandler = ^(id result, NSString *code, NSString *msg){
            
            //            NSDictionary *dic = result;
            //            dic = dic[@"data"];
            
            MyLog(@"手机号码修改成功=====\n\n%@", code);
            [JYTPublicClass showMessage:@"手机号码修改成功!"];
            
//            User *user =[[JYTUserManager shared] getUser];
//            user.phone = self.phoneTextfild.text;
        };
        
        manager.errorCallbackHandler = ^(NSString * code, NSString * msg) {
            MyLog(@"000000011111手机号码修改失败");
            if ([code isKindOfClass:[NSNull class]]) {
                MyLog(@"原因=====\n\n%@", msg);
            }else{
                if ([code isEqualToString:@"-1"]) {
                    [JYTPublicClass showMessage:@"服务器异常，请稍后再试！"];
                }else{
                    [JYTPublicClass showMessage:@"当前网络异常，请稍后再试！"];
                }
            }
        };
}

#pragma mark ----UITextFieldDelegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (range.length+range.location > textField.text.length) {
        return NO;
    }
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    if (textField==self.phoneTextfild){
        return newLength<=11;
    }else if (textField==self.testTextfild){
        return newLength<=6;
    }else{
        return newLength<=12;
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.phoneTextfild resignFirstResponder];
    [self.testTextfild resignFirstResponder];
    return YES;
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.phoneTextfild resignFirstResponder];
    [self.testTextfild resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
